package com.why.simpleboot.core.core.factory;

import com.why.simpleboot.core.annotation.aop.Aspect;
import com.why.simpleboot.core.common.utils.SimpleReflectUtils;
import com.why.simpleboot.core.core.aop.interceptor.DefaultAspectJInterceptor;
import com.why.simpleboot.core.core.aop.interceptor.Interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: why-simpleboot-framework
 * @description:
 * @author: @why
 * @create: 2021-05-26 21:26
 **/
public class InterceptorFactory {
    private static final Logger logger = LoggerFactory.getLogger(BeanFactory.class);
    private List<Interceptor> interceptors = new ArrayList<>();

    /**
     * 加载所有的拦截器
     *
     * @param basePackages
     */
    public void LoadInterceptors(
            ConcurrentHashMap<Class<? extends Annotation>, Set<Class<?>>>
                    classes, String... basePackages) {
        Set<Class<? extends Interceptor>> interceptors = SimpleReflectUtils.getSubclass(Interceptor.class, basePackages);
        /*
         * 加载路径下所有的拦截器实现类
         */
        for (Class<? extends Interceptor> interceptor : interceptors) {
            Interceptor instance = (Interceptor) SimpleReflectUtils.getInstance(interceptor);
            this.interceptors.add(instance);

        }

        /*
         加载所有被Aspect.class标注的类 ， adviceObject,就是代理类
         */
        Set<Class<?>> aspects = classes.get(Aspect.class);

        for (Class<?> adviceClass : aspects) {
            Object adviceObject = SimpleReflectUtils.getInstance(adviceClass);
            //封装被注解标注的实体类
            Interceptor defaultAspectjInterceptor = new DefaultAspectJInterceptor(adviceObject, adviceClass);
            this.interceptors.add(defaultAspectjInterceptor);
        }

//对拦截器做排序
        this.interceptors.stream().sorted(Comparator.comparing(Interceptor::getOrder));


    }

    public List<Interceptor> getInterceptors() {
        return interceptors;
    }
}
